<?php

namespace backend\controllers;

use common\models\Activity;
use Yii;
use common\models\Product;
use backend\models\ProductSearch;
use common\models\CouponCategory;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\web\Response;
use yii\bootstrap\ActiveForm;

/**
 * ProductController implements the CRUD actions for Product model.
 */
class ProductController extends Controller
{
    public $enableCsrfValidation = false;
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Lists all Product models.
     * @return mixed
     */
    public function actionSmallList()
    {
//        echo Yii::$app->session->get("checkgoods");
        $this->layout=false;
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('smalllist', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Product model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    /**
     * Creates a new Product model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionSmallCreate()
    {
        $this->layout=false;
        $model = new Product();

        if(Yii::$app->request->isPost){

            $model->pic = UploadedFile::getInstance($model,'pic');
            if($model->pic) {
                $data = $model->upload();
                if ($data) {

                    $model->image = $data;
                } else {
                    return "1" . json_encode($model->errors);
                }
            }
            $model->pic1 = UploadedFile::getInstance($model,'pic1');
            if($model->pic1) {
                $data = $model->upload1();
                if ($data) {

                    $model->share_img = $data;
                } else {
                    return "1" . json_encode($model->errors);
                }
            }

        }

        if ($model->load(Yii::$app->request->post())  && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
        $conponsCatalogrys=CouponCategory::find()->where(['local_mark_id'=>'tuangou'])->select("id,title")->all();
        $data=[];
        foreach($conponsCatalogrys as $conponsCatalogry){
            $data[$conponsCatalogry->id]=$conponsCatalogry->title;
        }

        return $this->render('smallcreate', [
            'model' => $model,
            'data'=>$data
        ]);
    }
    /**
     * Updates an existing Product model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionSmallUpdate($id)
    {
        $this->layout=false;
        $model = $this->findModel($id);
        if(Yii::$app->request->isPost){
            $model->pic = UploadedFile::getInstance($model,'pic');
            if($model->pic) {
                $data = $model->upload();
                if ($data) {

                    $model->image = $data;
                } else {
                    return json_encode($model->errors);
                }
            }
            $model->pic1 = UploadedFile::getInstance($model,'pic1');
            if($model->pic1) {
                $data = $model->upload1();
                if ($data) {

                    $model->share_img = $data;
                } else {
                    return json_encode($model->errors);
                }
            }
        }
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
        $conponsCatalogrys=CouponCategory::find()->where(['local_mark_id'=>'tuangou'])->orWhere(['local_mark_id'=>'tuangou_'.$model->activity_id])->select("id,title")->all();
        $data=[];
        foreach($conponsCatalogrys as $conponsCatalogry){
            $data[$conponsCatalogry->id]=$conponsCatalogry->title;
        }

// var_dump($data);exit;
        return $this->render('smallupdate', [
            'model' => $model,
            'data'=>$data
        ]);
    }
    /**
     * Deletes an existing Product model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {

        $activitys=Activity::find()->where('goods REGEXP \'^([1234567890]+,){0,}'.$id.'(,[1234567890]+){0,}$\'')->all();
        foreach($activitys as $activity){
            $goods = $activity->goods;
            $arr=explode(",",$goods);

            foreach($arr as $key=>$val){
                if($val==$id){
                    unset($arr[$key]);
                }
            }

            $goods = implode(",",$arr);

            $model=Activity::findOne($activity->id);
            $model->goods = $goods;
            if(!$model->save()){
             print_r($model->getErrors());
            }
        }

        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

    /**
     * Finds the Product model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Product the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Product::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
    public function actionTest(){
        $tmp = Yii::$app->session->get("checkgoods");
        var_dump($tmp);
    }
    public function actionToggle($id){
        $tmp = Yii::$app->session->get("checkgoods");

        $arr = explode(",",$tmp);

        if(empty($arr)){
            $arr[]=$id;
        }elseif(in_array($id,$arr)){
            foreach($arr as $key=>$item){
                if($id==$item){
                    unset($arr[$key]);
                }
            }
        }else{
            $arr[]=$id;
        }
        $result=implode(",",$arr);
        if(substr($result,0,1)==","){$result=substr($result,1);}
        if(substr($result,-1)==","){$result=substr($result,0,-1);}
        Yii::$app->session->set("checkgoods",$result);
        return $result;
    }
    //该方法是异步校验字段
    public function actionValidate(){
        $model = new Product();
        if (Yii::$app->request->isPost && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        Yii::$app->response->format = Response::FORMAT_JSON;
        return [];
    }

    public function actionUpload(){

        if ($_FILES["Product"]["error"]['pic'] > 0)
        {
//            echo "Error: " . $_FILES["file"]["error"]['pic'] . "<br />";
            Yii::$app->response->format=Response::FORMAT_JSON;
            return ['result'=>'error','msg'=>$_FILES["file"]["error"]['pic']];
        }
        else
        {
//            echo "Upload: " . $_FILES["Product"]["name"]['pic'] . "<br />";
//            echo "Type: " . $_FILES["Product"]["type"]['pic'] . "<br />";
//            echo "Size: " . ($_FILES["Product"]["size"]['pic'] / 1024) . " Kb<br />";
//            echo "Stored in: " . $_FILES["Product"]["tmp_name"]['pic'];
            $ext  = explode("/",$_FILES["Product"]["type"]['pic'])[1];
            $savePath = 'wumaituangou/'.date('Ymd').'/image/';
            $filename = uniqid().'.'.$ext;

            $stream = fopen($_FILES["Product"]["tmp_name"]['pic'], 'r+');
            if (!Yii::$app->awss3Fs->putStream($savePath . $filename, $stream)) {
                throw new yii\web\ServerErrorHttpException('File upload failed.');
            }
            @unlink($_FILES["Product"]["tmp_name"]['pic']);
//            var_dump(getenv('OSS_FILE_ROOT') . $savePath . $filename);exit;
            Yii::$app->response->format=Response::FORMAT_JSON;
            return ['result'=>'success','url'=>getenv('OSS_FILE_ROOT') . $savePath . $filename];
        }




    }
    public function actionUpload1(){

        if ($_FILES["Product"]["error"]['pic1'] > 0)
        {
//            echo "Error: " . $_FILES["file"]["error"]['pic1'] . "<br />";
            Yii::$app->response->format=Response::FORMAT_JSON;
            return ['result'=>'error','msg'=>$_FILES["file"]["error"]['pic1']];
        }
        else
        {
//            echo "Upload: " . $_FILES["Product"]["name"]['pic1'] . "<br />";
//            echo "Type: " . $_FILES["Product"]["type"]['pic1'] . "<br />";
//            echo "Size: " . ($_FILES["Product"]["size"]['pic1'] / 1024) . " Kb<br />";
//            echo "Stored in: " . $_FILES["Product"]["tmp_name"]['pic1'];
            $ext  = explode("/",$_FILES["Product"]["type"]['pic1'])[1];
            $savePath = 'wumaituangou/'.date('Ymd').'/image/';
            $filename = uniqid().'.'.$ext;

            $stream = fopen($_FILES["Product"]["tmp_name"]['pic1'], 'r+');
            if (!Yii::$app->awss3Fs->putStream($savePath . $filename, $stream)) {
                throw new yii\web\ServerErrorHttpException('File upload failed.');
            }
            @unlink($_FILES["Product"]["tmp_name"]['pic1']);
//            var_dump(getenv('OSS_FILE_ROOT') . $savePath . $filename);exit;
            Yii::$app->response->format=Response::FORMAT_JSON;
            return ['result'=>'success','url'=>getenv('OSS_FILE_ROOT') . $savePath . $filename];
        }




    }
}
